package com.xius.interceptor;

import cn.hutool.core.exceptions.ValidateException;
import com.xius.common.XiusValidata;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FormInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws ClassNotFoundException, NoSuchMethodException,IllegalAccessException {
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        if (method.isAnnotationPresent(XiusValidata.class)) {
            XiusValidata xiusValidata = method.getAnnotation(XiusValidata.class);

            Class<?> className = xiusValidata.excute();

            //Object invoke = ClassUtil.invoke(className.getName(), className.getName()+"."+method.getName(), false, httpServletRequest);

            try {
                Method method2 = className.getMethod(method.getName(),HttpServletRequest.class);
                //获取参数
                Constructor<?> constructor = className.getConstructor();
                Object o = null;
                try {
                    o = constructor.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }

                method2.invoke(o,httpServletRequest);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                if(cause instanceof ValidateException){
                    throw (ValidateException)cause;
                }
            }

            /* Object o = className.newInstance();*/
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}